package uniLearn.control;

import java.sql.SQLException;
import uniLearn.db.DBConnection;

/**
 * @author ttw1988
 *
 */
public abstract class DataControl {

	//the Root of the storage
	protected static String ROOT_DIR_PATH = "E:\\Uni_Learn_Storage";
	
	//variable
	protected DBConnection dbCon;
	
	/**Close all Database Object that used in this Control Object 
	 * @throws SQLException - Throw the SQL Exception by Database Object
	 */
	public void closeDBConnection() throws SQLException {
		if(dbCon != null && !dbCon.isClosed())
			dbCon.close();
	}
	

	/** Set & Start the Database connection
	 * @throws SQLException SQL Exception of start database connection
	 * @throws Exception Problem of using MYSQL Control
	 */
	protected final void startConnection() throws SQLException, Exception {
		try {
			if(this.dbCon != null && !this.dbCon.isClosed()) {
				//still using the connection 
				return;
			}
			this.dbCon = new DBConnection();
		} catch (SQLException e) {
			throw e;
		} catch (ClassNotFoundException e) {
			throw new Exception("Can't use the MYSQL Connector.");
		}
			
	}
	
	/**
	 * @param str A String for checking
	 * @param maxLength The Maximum length of the String 
	 * @return If have any error, return True
	 */
	protected static boolean checkLength(String str, int maxLength) {
		return (str == null || str.isEmpty() || str.length() > maxLength);
	}

	/**
	 * @param str A String for checking
	 * @return If have any error, return True
	 */
	protected static boolean checkLength(String str) {
		return (str == null || str.isEmpty());
	}
	
	/**
	 * @param oldSQL the original SQL Command
	 * @param numElement How much element in the "WHERE IN" Statement 
	 * @return the new SQL Command
	 */
	protected static String regenSQL(String oldSQL, int numElement) {
		StringBuilder tmp = new StringBuilder("(?");
		for(int i = 1; i < numElement; i++)
			tmp.append(", ?");
		tmp.append(')');
		
		return oldSQL.replaceFirst("(\\(\\?\\))", tmp.toString());
	}

}